package com.bosssoft.boss_exam_web.Controller;

import com.bosssoft.boss_exam_core.enums.ResultCode;
import com.bosssoft.boss_exam_core.exception.DeleteEntityException;
import com.bosssoft.boss_exam_core.exception.QueryDataException;
import com.bosssoft.boss_exam_core.exception.ReflectionException;
import com.bosssoft.boss_exam_core.exception.UpdateEntityException;
import com.bosssoft.boss_exam_core.util.web.ResponseUtil;
import com.bosssoft.boss_exam_core.validator.Order;
import com.bosssoft.boss_exam_core.validator.Sort;
import com.bosssoft.boss_exam_db.entity.Admin;
import com.bosssoft.boss_exam_db.entity.Role;
import com.bosssoft.boss_exam_db.service.busines.AdminService;
import com.bosssoft.boss_exam_web.common.annotation.LoginAdmin;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/***
 * @Author lys(cherish)
 * @Phone 17720799636
 * @Date  2019/3/13
 * @Description 登入控制器
 * @since JDK 1.8
 **/
@RestController
@Validated
@Slf4j
public class AdminController {

    // 引入管理员服务
    @Autowired
    private AdminService adminService;


    @ApiOperation(value="管理员查询", notes="可根据管理员ID查询" ,httpMethod="GET",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="adminId", value="管理员ID", dataType = "String", required=true, dataTypeClass=String.class),
            @ApiImplicitParam(name="page", value="当前页码", dataType = "String", required=false, dataTypeClass=Integer.class),
            @ApiImplicitParam(name="limit", value="每页显示条数", dataType = "String", required=false, dataTypeClass=Integer.class),
            @ApiImplicitParam(name="sort", value="排序依据", dataType = "String", required=false, dataTypeClass=String.class),
            @ApiImplicitParam(name="order", value="排序方式", dataType = "String", required=false, dataTypeClass=String.class)
    })
    @GetMapping("/admin/admin/list")
    public Object list(@LoginAdmin String adminId,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        PageInfo<Admin> adminPageInfo=adminService.queryByCondition(page,limit,sort,order);
        Map<String, Object> data = new HashMap<>();
        data.put("total", adminPageInfo.getTotal());
        data.put("items", adminPageInfo.getList());
        return ResponseUtil.ok(data);
    }


    @ApiOperation(value="创建管理员", notes="创建一条管理员信息" ,httpMethod="POST",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="admin", value="管理员信息", dataType = "Admin", required=true, dataTypeClass=Admin.class),
    })
    @PostMapping("/admin/admin/create")
    public Object create(@LoginAdmin String adminId, @RequestBody Admin admin) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        int recordNum = adminService.saveNotNull(admin);
        if(recordNum==1){
            return ResponseUtil.ok();
        }else{
            log.error("【系统错误】 保存公司失败");
            throw  new UpdateEntityException();
        }
    }

    @ApiOperation(value="读取一条管理员信息", notes="根据ID读取一条管理员信息" ,httpMethod="GET",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="admin", value="管理员ID", dataType = "String", required=true, dataTypeClass=String.class),
    })
    @GetMapping("/admin/admin/read")
    public Object read(@LoginAdmin Integer adminId, @NotNull Integer id) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        Admin admin = null;
        try {
            admin = adminService.selectByKey(id);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            log.error("【系统错误】 反射操作异常" + e);
            throw new ReflectionException(ResultCode.SYSTEM_INNER_ERROR);
        } catch (Exception e) {
            log.error("【业务错误】 读取集团异常" + e);
            throw new QueryDataException();
        }
        return ResponseUtil.ok(admin);
    }
    @ApiOperation(value="更新管理员信息", notes="根据一条管理员信息" ,httpMethod="GET",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="admin", value="管理员信息", dataType = "Admin", required=true, dataTypeClass=Admin.class),
    })
    @PostMapping("/admin/admin/update")
    public Object update(@LoginAdmin Integer adminId, @RequestBody Admin admin) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        int recordNum = adminService.updateNotNull(admin);
        if(recordNum==1){
            return ResponseUtil.ok();
        }else{
            log.error("【系统错误】 更新管理员失败");
            throw  new UpdateEntityException();
        }
    }

    @ApiOperation(value="删除管理员信息", notes="根据管理员ID删除管理员信息" ,httpMethod="POST",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="id", value="管理员ID", dataType = "String", required=true, dataTypeClass=String.class),
    })
    @PostMapping("/admin/admin/delete")
    public Object delete(@LoginAdmin Integer adminId, @RequestParam String id) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        Admin admin = new Admin();
        admin.setId(id);
        try {
            int i = adminService.deleteForLogic(admin);
            if(i==1){
                return ResponseUtil.ok();
            }else {
                log.info("【业务错误】 逻辑删除管理员失败");
                throw  new DeleteEntityException();
            }
        } catch (NoSuchMethodException|IllegalAccessException|InvocationTargetException e) {
            log.error("【系统错误】 反射操作异常"+e);
            throw  new ReflectionException(ResultCode.SYSTEM_INNER_ERROR);
        }
    }
    @ApiOperation(value="获取当前管理员信息", notes="根据当前登入的管理员获取管理员信息" ,httpMethod="GET",response = Object.class)
    @ApiImplicitParams({
    })
    @GetMapping("/admin/admin/info")
    public Object getInfo(@LoginAdmin String adminId){
        Admin admin = null;
        try {
            admin = adminService.selectByKey(adminId);
        }catch (NoSuchMethodException|IllegalAccessException|InvocationTargetException e) {
            log.error("【系统错误】 反射操作异常"+e);
            throw  new ReflectionException(ResultCode.SYSTEM_INNER_ERROR);
        }catch (Exception e) {
            log.info("【业务错误】 获取管理员信息异常"+e);
            throw  new QueryDataException();
        }
        //屏蔽密码
        admin.setPassword("");
        //// FIXME: 2019/3/14 当前是将用户的角色设置为admin ,

//        String[] objects =(String[]) roles.stream().map(role -> role.getName()).toArray();
//        admin.setRoles(roles);

        Role role = new Role();
        role.setName("admin");
        ArrayList<Role> roles = new ArrayList<>();
        roles.add(role);
        admin.setRoles(roles);
        return  ResponseUtil.ok("当前用户信息",admin);
    }


}
